package com.example.tellwin.home.act;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.tellwin.MainApplication;
import com.example.tellwin.MediaActivity;
import com.example.tellwin.PhotoActivity;
import com.example.tellwin.R;
import com.example.tellwin.base.CpBaseActivty;
import com.example.tellwin.base.DaggerRxComponent;
import com.example.tellwin.common.Common;
import com.example.tellwin.event.ActDetailEvent;
import com.example.tellwin.event.CallEvent;
import com.example.tellwin.home.adpater.VoteAdapter;
import com.example.tellwin.home.adpater.WorkAdapter;
import com.example.tellwin.home.bean.ActivitiesBean;
import com.example.tellwin.home.bean.ActivityDetailContentBean;
import com.example.tellwin.home.bean.VoteBean;
import com.example.tellwin.home.bean.WorkBean;
import com.example.tellwin.home.contract.ActivityDetailContract;
import com.example.tellwin.home.presenter.ActivityDetailPresenter;
import com.example.tellwin.utils.CommonUtils;
import com.example.tellwin.utils.GlideUtils;
import com.example.tellwin.utils.ImageUtils;
import com.example.tellwin.utils.ToastUtil;
import com.example.tellwin.view.ContentTextView;
import com.example.tellwin.view.ShareDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ActDetailActivity extends CpBaseActivty implements ActivityDetailContract.View {

    @BindView(R.id.act_title_tv)
    TextView actTitleTv;
    @BindView(R.id.act_iv)
    ImageView actIv;
    @BindView(R.id.act_share_iv)
    ImageView actShareIv;
    @BindView(R.id.act_number_tv)
    TextView actNumberTv;
    @BindView(R.id.act_introduction_tv)
    TextView actIntroductionTv;
    @BindView(R.id.my_work_iv)
    ImageView myWorkIv;
    @BindView(R.id.my_poll_text)
    TextView myPollText;
    @BindView(R.id.my_poll_tv)
    TextView myPollTv;
    @BindView(R.id.my_ranking_text)
    TextView myRankingText;
    @BindView(R.id.my_ranking_tv)
    TextView myRankingTv;
    @BindView(R.id.my_vote_rv)
    RecyclerView myVoteRv;
    @BindView(R.id.work_rv)
    RecyclerView workRv;
    @BindView(R.id.vote_ll)
    LinearLayout voteLl;
    @BindView(R.id.act_introduce_rl)
    RelativeLayout actIntroduceRl;
    @BindView(R.id.join_act_tv)
    TextView joinActTv;
    @BindView(R.id.participator_ctv)
    ContentTextView participatorCtv;
    @BindView(R.id.now_number_of_participants_ctv)
    ContentTextView nowNumberOfParticipantsCtv;
    @BindView(R.id.number_of_participants_ctv)
    ContentTextView numberOfParticipantsCtv;
    @BindView(R.id.active_work_form_ctv)
    ContentTextView activeWorkFormCtv;
    @BindView(R.id.active_prize_ctv)
    ContentTextView activePrizeCtv;
    @BindView(R.id.prize_give_way_ctv)
    ContentTextView prizeGiveWayCtv;
    @BindView(R.id.prize_number_ctv)
    ContentTextView prizeNumberCtv;
    @BindView(R.id.get_points_by_voting_ctv)
    ContentTextView getPointsByVotingCtv;
    @BindView(R.id.guess_get_points_ctv)
    ContentTextView guessGetPointsCtv;
    @BindView(R.id.deadline_ctv)
    ContentTextView deadlineCtv;
    @BindView(R.id.active_introduce_tv)
    TextView activeIntroduceTv;
    @BindView(R.id.my_work_rl)
    RelativeLayout myWorkRl;
    @BindView(R.id.work_list_ll)
    LinearLayout workListLl;
    @BindView(R.id.activity_detail_ll)
    LinearLayout activityDetailLl;
    @BindView(R.id.active_introduce_rl)
    RelativeLayout activeNotJoinIntroduceRl;
    @BindView(R.id.my_work_rank_rl)
    RelativeLayout myWorkRankRl;
    @BindView(R.id.load_tv)
    TextView loadTv;
    @BindView(R.id.voice_view)
    LinearLayout voiceLl;

    private WorkAdapter workAdapter;
    private List<WorkBean> workBeanList = new ArrayList<>();
    private VoteAdapter voteAdapter;
    private List<VoteBean> voteBeanList = new ArrayList<>();

    int type = 1;

    private ActivityDetailContentBean activityDetailContentBean;

    @Inject
    ActivityDetailPresenter mPresenter;
    private MediaPlayer mediaPlayer;

    private Handler uiHander = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 1001:
                    if (ActDetailActivity.this.isFinishing()) {
                        return;
                    }
                    loadTv.setVisibility(View.INVISIBLE);
                    Bitmap bitmap = (Bitmap) msg.obj;
                    Glide.with(ActDetailActivity.this).load(bitmap).into(myWorkIv);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_act_detail);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initViews();
        initEvents();
        initDatas();
    }

    @Override
    protected void initViews() {
        DaggerRxComponent.builder()
                .baseAppComponent(MainApplication.getAppComponent())
                .build()
                .inject(this);
        mPresenter.attachView(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        myVoteRv.setLayoutManager(linearLayoutManager);
        voteAdapter = new VoteAdapter();
        myVoteRv.setAdapter(voteAdapter);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
        workRv.setLayoutManager(gridLayoutManager);
        workRv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                int position = parent.getChildAdapterPosition(view);
                outRect.bottom = getResources().getDimensionPixelOffset(R.dimen.dp_15);
                if (position % 2 == 0) {
                    outRect.right = getResources().getDimensionPixelOffset(R.dimen.dp_4_5);
                } else {
                    outRect.left = getResources().getDimensionPixelOffset(R.dimen.dp_4_5);
                }
            }
        });
        workAdapter = new WorkAdapter();
        workRv.setAdapter(workAdapter);
    }

    @Override
    protected void initEvents() {
        actIntroductionTv.setOnClickListener(v -> {
            Intent intent = new Intent(this, ActIntroductionActivity.class);
            intent.putExtra(Common.ACTIVITY, activityDetailContentBean);
            startActivity(intent);
        });
        workAdapter.setWorkListener(new WorkAdapter.WorkListener() {
            @Override
            public void onItemVote(int position, WorkBean workBean) {
                mPresenter.workVote(workBean.getParticipateId());
            }

            @Override
            public void onItemClick(int position, WorkBean workBean) {
                if (activityDetailContentBean.getActivityDetails().getParticipateCondition() == 0) {
                    Intent intent = new Intent(ActDetailActivity.this, PhotoActivity.class);
                    ArrayList<String> photoPaths = new ArrayList();
                    photoPaths.add(workBean.getWorks());
                    intent.putExtra(Common.PHOTO_PATH, photoPaths);
                    intent.putExtra(Common.POSITION, position);
                    startActivity(intent);
                } else if (activityDetailContentBean.getActivityDetails().getParticipateCondition() == 1) {
                    playVoice(workBean.getWorks());
                } else if (activityDetailContentBean.getActivityDetails().getParticipateCondition() == 2) {
                    Intent intent1 = new Intent(ActDetailActivity.this, MediaActivity.class);
                    intent1.putExtra(Common.MEDIA_PATH, activityDetailContentBean.getUserParticipate().getWorks());
                    startActivity(intent1);
                }
            }
        });
    }

    @Override
    protected void initDatas() {
        ActivitiesBean activitiesBean = (ActivitiesBean) getIntent().getSerializableExtra(Common.ACTIVITY);
        String actId = getIntent().getStringExtra(Common.ACTIVITY_ID);
        if (activitiesBean != null) {
            mPresenter.activiteDetail(activitiesBean.getActivityId());
            setTitle(activitiesBean.getActivityName());
        } else {
            mPresenter.activiteDetail(actId);
        }

    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @OnClick({R.id.act_share_iv, R.id.join_act_tv, R.id.my_work_iv, R.id.voice_view})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.act_share_iv:
                ShareDialog shareDialog = new ShareDialog(this, 1, activityDetailContentBean.getActivityDetails().getActivityId(), activityDetailContentBean.getActivityDetails().getActivityName());
                shareDialog.show();
                break;
            case R.id.join_act_tv:
                Intent intent = new Intent(this, UploadWorkActivity.class);
                intent.putExtra(Common.ACTIVITY, activityDetailContentBean);
                startActivity(intent);
                break;
            case R.id.my_work_iv:
                if (activityDetailContentBean.getActivityDetails().getParticipateCondition() == 0) {
                    Intent intent1 = new Intent(this, PhotoActivity.class);
                    ArrayList<String> photoPaths = new ArrayList<>();
                    photoPaths.add(activityDetailContentBean.getUserParticipate().getWorks());
                    intent1.putExtra(Common.PHOTO_PATH, photoPaths);
                    startActivity(intent1);
                } else if (activityDetailContentBean.getActivityDetails().getParticipateCondition() == 2) {
                    Intent intent1 = new Intent(this, MediaActivity.class);
                    intent1.putExtra(Common.MEDIA_PATH, activityDetailContentBean.getUserParticipate().getWorks());
                    startActivity(intent1);
                } else {
                    playVoice(activityDetailContentBean.getUserParticipate().getWorks());
                }
                break;
            case R.id.voice_view:
                playVoice(activityDetailContentBean.getUserParticipate().getWorks());
                break;
        }
    }

    private void playVoice(String path) {
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
        }
        try {
            mediaPlayer.stop();
            mediaPlayer.reset();
            mediaPlayer.setDataSource(path);//设置播放来源
            mediaPlayer.prepareAsync();//异步准备
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                //异步准备监听
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    mediaPlayer.start();//播放
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void activiteDetailResult(ActivityDetailContentBean activityDetailContentBean) {
        this.activityDetailContentBean = activityDetailContentBean;
        ActivityDetailContentBean.ActivityDetailsBean activityDetailsBean = activityDetailContentBean.getActivityDetails();
        setTitle(activityDetailsBean.getActivityName());
        GlideUtils.LoadImage(this, activityDetailsBean.getActivityPic(), actIv);
        voteLl.setVisibility(View.GONE);
        if (activityDetailsBean.getActivityStatus() == 1) {//报名
            if (activityDetailContentBean.getIsparticipate() == 1) {//参加
                myWorkRl.setVisibility(View.VISIBLE);
                activityDetailLl.setVisibility(View.VISIBLE);
                activeNotJoinIntroduceRl.setVisibility(View.VISIBLE);
                joinActTv.setVisibility(View.GONE);
                actIntroduceRl.setVisibility(View.GONE);
                workListLl.setVisibility(View.GONE);
                getPointsByVotingCtv.setVisibility(View.GONE);
                guessGetPointsCtv.setVisibility(View.GONE);
                myWorkRankRl.setVisibility(View.GONE);
                setActityDetailData(activityDetailsBean);
                joinShowView(activityDetailContentBean);
            } else {//未参加
                getPointsByVotingCtv.setVisibility(View.VISIBLE);
                guessGetPointsCtv.setVisibility(View.VISIBLE);
                joinActTv.setVisibility(View.VISIBLE);
                activityDetailLl.setVisibility(View.VISIBLE);
                activeNotJoinIntroduceRl.setVisibility(View.VISIBLE);
                actIntroduceRl.setVisibility(View.GONE);
                myWorkRl.setVisibility(View.GONE);
                workListLl.setVisibility(View.GONE);
                setActityDetailData(activityDetailsBean);
            }

        } else if (activityDetailsBean.getActivityStatus() == 2) {//投票
            if (activityDetailContentBean.getIsparticipate() == 1) {//参加
                myWorkRl.setVisibility(View.VISIBLE);
            } else {
                myWorkRl.setVisibility(View.GONE);
            }
            actIntroduceRl.setVisibility(View.VISIBLE);
            activityDetailLl.setVisibility(View.GONE);
            activeNotJoinIntroduceRl.setVisibility(View.GONE);
            joinActTv.setVisibility(View.GONE);
            actIntroduceRl.setVisibility(View.VISIBLE);
            setMyWork();
            if (activityDetailContentBean.getParticipateList() != null && activityDetailContentBean.getParticipateList().size() > 0) {
                workListLl.setVisibility(View.VISIBLE);
                workAdapter.setWorkBeans(activityDetailContentBean.getParticipateList(), false, 1);
            } else {
                workListLl.setVisibility(View.GONE);
            }
            joinShowView(activityDetailContentBean);
        } else {//结束
            if (activityDetailContentBean.getIsparticipate() == 1) {//参加
                myWorkRl.setVisibility(View.VISIBLE);
            } else {
                myWorkRl.setVisibility(View.GONE);
            }
            actIntroduceRl.setVisibility(View.VISIBLE);
            activityDetailLl.setVisibility(View.GONE);
            activeNotJoinIntroduceRl.setVisibility(View.GONE);
            joinActTv.setVisibility(View.GONE);
            if (activityDetailContentBean.getParticipateList() != null && activityDetailContentBean.getParticipateList().size() > 0) {
                workListLl.setVisibility(View.VISIBLE);
                workAdapter.setWorkBeans(activityDetailContentBean.getParticipateList(), false, 1);
            } else {
                workListLl.setVisibility(View.GONE);
            }
            setMyWork();
            joinShowView(activityDetailContentBean);
        }
        actNumberTv.setText(Html.fromHtml("<font color='#D94850'>" + activityDetailContentBean.getParticipateCount() + "</font>参加\t\t<font color='#D94850'>" + activityDetailContentBean.getVoteCount() + "</font>投票"));
    }

    @Override
    public void workVoteSuccess() {
        initDatas();
    }

    private void joinShowView(ActivityDetailContentBean activityDetailContentBean) {
        if (TextUtils.isEmpty(activityDetailContentBean.getUserParticipate().getWorks())) {
            return;
        }
        if (activityDetailContentBean.getActivityDetails().getParticipateCondition() == 0) {
            voiceLl.setVisibility(View.GONE);
            GlideUtils.LoadImage(this, activityDetailContentBean.getUserParticipate().getWorks(), myWorkIv);
        } else if (activityDetailContentBean.getActivityDetails().getParticipateCondition() == 1) {
            voiceLl.setVisibility(View.VISIBLE);
        } else if (activityDetailContentBean.getActivityDetails().getParticipateCondition() == 2) {
            voiceLl.setVisibility(View.GONE);
            loadTv.setVisibility(View.VISIBLE);
            if (activityDetailContentBean.getUserParticipate().getWorks() != null) {
                new Thread(() -> {
                    Bitmap bitmap = ImageUtils.getNetVideoBitmap(activityDetailContentBean.getUserParticipate().getWorks());
                    Message message = new Message();
                    message.what = 1001;
                    message.obj = bitmap;
                    uiHander.sendMessage(message);
                }).start();
            }
        }
    }

    private void setMyWork() {
        if (activityDetailContentBean.getUserParticipate() != null && !TextUtils.isEmpty(activityDetailContentBean.getUserParticipate().getWorks())) {
            myWorkRl.setVisibility(View.VISIBLE);
            myPollTv.setText(activityDetailContentBean.getUserParticipate().getVoteCount());
            myRankingTv.setText(activityDetailContentBean.getUserParticipate().getRanking() + "");
        } else {
            myWorkRl.setVisibility(View.GONE);
        }
    }

    private void setActityDetailData(ActivityDetailContentBean.ActivityDetailsBean activityDetailsBean) {
        participatorCtv.setTvStr(CommonUtils.getParticipateStr(activityDetailsBean.getParticipateType()));
        nowNumberOfParticipantsCtv.setTvStr(activityDetailContentBean.getParticipateCount() + "");
        numberOfParticipantsCtv.setTvStr(activityDetailsBean.getParticipantsNum() + "");
        activeWorkFormCtv.setTvStr(CommonUtils.getParticipateCondition(activityDetailsBean.getParticipateCondition()));
        activePrizeCtv.setTvStr(activityDetailsBean.getActivityPrize());
        prizeGiveWayCtv.setTvStr(activityDetailsBean.getGiveMode());
        prizeNumberCtv.setTvStr(activityDetailsBean.getAwardsCount() + "");
        getPointsByVotingCtv.setTvStr(activityDetailsBean.getVoteIntegral() + "");
        guessGetPointsCtv.setTvStr(activityDetailsBean.getRankingIntegral());
        deadlineCtv.setTvStr(activityDetailsBean.getVoteTime());
        activeIntroduceTv.setText(activityDetailsBean.getActivityIntroduce());
    }

    @Subscribe
    public void onEvent(ActDetailEvent event) {
        initDatas();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }
}
